﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LootPoints.Security;

namespace LootPoints.Warcraft
{
    public static class EpGpLog
    {
        /// <summary>
        /// Will save the log unless its a log from a different guild and will not save non-guild members.
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public static bool SaveLog(string log)
        {
            //try
            //{
                BattleNet armory = new BattleNet();

                // Get guildmembers
                Dictionary<string, string[]> members = armory.GetGuildMembers();

                // Convert the result to a filtered list
                List<string> filteredValues = armory.FilterValues(log);

                ModelContainer context = new ModelContainer();

                // Gets the membernames already registered
                List<string> membernames = (from c in context.Character select c.Name).ToList();

                bool inRoster = false;
                bool inLoot = false;

                for (int i = 0; i < filteredValues.Count; i++)
                {
                    // Check if correct guild
                    if (filteredValues[i] == "guild")
                        if (filteredValues[i + 1].ToLower() != "exploding sheep inc")
                            throw new Exception("Wrong guild!");

                    // Gets the epgp...
                    if (inRoster)
                    {
                        // ...from guildmembers only
                        if (members.Keys.Contains(filteredValues[i].ToString()) || membernames.Contains(filteredValues[i].ToString()))
                        {
                            string cn = filteredValues[i].ToString();
                            
                            Character character = (from c in context.Character where c.Name == cn select c).FirstOrDefault();
                            if (character == null)
                            {
                                character = new Character();
                                character.Name = filteredValues[i].ToString();
                                i++;
                                character.EP = Convert.ToInt32(filteredValues[i]);
                                i++;
                                character.GP = Convert.ToInt32(filteredValues[i]);
                                
                                character.Admin = false;
                                character.Class = members[character.Name][1];
                                character.Race = members[character.Name][0];
                                character.Rank = members[character.Name][3];
                                character.Level = Convert.ToInt32(members[character.Name][2]);
                                character.Email = "";
                                character.Password = Hashing.CreateHash("sheep");
                                character.Reset = false;

                                context.Character.Add(character);
                            }
                            else
                            {
                                i++;
                                character.EP = Convert.ToInt32(filteredValues[i]);
                                i++;
                                character.GP = Convert.ToInt32(filteredValues[i]);
                            }
                        }
                    }

                    context.SaveChanges();

                    // Gets the loot...
                    if (inLoot)
                    {
                        // ...from guildmembers only
                        if (members.Keys.Contains(filteredValues[i + 1]) || membernames.Contains(filteredValues[i + 1]))
                        {
                            DateTime dt = UnixTimeStampToDateTime(Convert.ToDouble(filteredValues[i]));
                            //if ((from c in context.LootLog where c.Datetime == dt select c).FirstOrDefault() == null)
                            //{
                                LootLog llog = new LootLog();

                                llog.Datetime = dt;
                                i++;
                                string cn = filteredValues[i].ToString();
                                llog.Character = (from c in context.Character where c.Name == cn select c).FirstOrDefault();
                                i++;
                                llog.ArmoryId = Convert.ToInt32(filteredValues[i]);
                                llog.Item = armory.GetItemName(llog.ArmoryId);
                                i++;
                                llog.GP = Convert.ToInt32(filteredValues[i]);

                                context.LootLog.Add(llog);
                            //}
                        }
                    }

                    if (filteredValues[i] == "roster") { inRoster = true; inLoot = false; }
                    if (filteredValues[i] == "loot") { inRoster = false; inLoot = true; }
                    if (filteredValues[i] == "decay_p") { inRoster = false; inLoot = false; }
                    if (filteredValues[i + 1] == "timestamp") break;
                }

                context.SaveChanges();

                return true;
            //}
            //catch { return false; }
        }

        public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
        {
            // Unix timestamp is seconds past epoch
            System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
            return dtDateTime;
        }
    }
}